<template>
  <div>
    <el-dialog
      :visible.sync="openProcess"
      :fullscreen="true"
      :destroy-on-close="true"
      :show-close="false">
      <div style="
        border-bottom: 1px solid rgb(232,232,232);
        position: absolute;
        top: 0; left: 0;
        height: 70px; width: 100%;
        line-height: 70px; padding-left: 20px; padding-right: 20px;">
        <span style="font-weight: bold; font-size: 20px;">{{ processTitle }}</span>

        <div style="float:right;" v-show="startProcess">
          <el-select v-model="processKey" placeholder="请选择流程" @change="handleChangeProcessKey"
                     style="margin-right: 10px;">
            <el-option
              v-for="item in processList"
              :key="item.processTitle"
              :label="item.processTitle"
              :value="item.processKey">
            </el-option>
          </el-select>
          <el-select v-model="processVersion" placeholder="版本" @change="handleChangeProcessVersion"
                     style="margin-right: 10px; width: 200px;">
            <el-option
              v-for="item in processVersionList"
              :key="item.versionTag"
              :label="item.versionTag"
              :value="item.versionNum">
              <span style="float: left">{{ item.versionTag }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px">{{ item.versionNum }}</span>
            </el-option>
          </el-select>
          <el-button type="primary" icon="el-icon-edit"
                     @click="handleCreateProcess">启动</el-button>
          <el-button plain icon="el-icon-close" @click="handleCloseProcess"></el-button>
        </div>

        <div style="float:right;" v-show="!startProcess">
          <el-button type="primary" icon="el-icon-edit"
                     @click="handleCompleteButton" v-show="isHandle">{{ complete }}</el-button>
          <el-button type="primary" icon="el-icon-edit" v-show="authList.includes('完成委托')"
                     @click="handleCompleteDelegateButton">完成委托</el-button>
          <el-button icon="el-icon-add-location" v-show="authList.includes('加签')"
                     @click="handleAddSignButton">加签</el-button>
          <el-button icon="el-icon-delete-location" v-show="authList.includes('减签')"
                     @click="handleDeleteSignButton">减签</el-button>
          <el-button icon="el-icon-s-custom" v-show="authList.includes('委托')"
                     @click="handleDelegateButton">委托</el-button>
          <el-button icon="el-icon-refresh-left" v-show="authList.includes('取消委托')"
                     @click="handleCancelDelegateButton">取消委托</el-button>
          <el-button icon="el-icon-s-check" v-show="authList.includes('转办')"
                     @click="handleRelayCompleteButton">转办</el-button>
          <el-button icon="el-icon-picture-outline-round"
                     @click="handleProcessFollowButton">流程跟踪</el-button>
          <el-button plain icon="el-icon-close" @click="handleCloseProcess"></el-button>
        </div>
      </div>

      <el-card class="box-card" style="margin: 40px;" v-if="openStartForm">
        <div slot="header" class="clearfix">
          <span style="font-weight: bold; font-size: 20px;">启动表单</span>
        </div>
        <div class="text item">
          <div class="startForm" ref="startForm"></div>
        </div>
      </el-card>

      <el-card class="box-card" style="margin: 40px;" v-if="openTaskForm && !startProcess">
        <div slot="header" class="clearfix">
          <span style="font-weight: bold; font-size: 20px;">{{ taskFormTitle }}</span>
        </div>
        <div class="text item">
          <div class="taskForm" ref="taskForm"></div>
        </div>
      </el-card>

      <el-card class="box-card" style="margin: 40px;" v-for="(item, index) in finishForm" :key="index" v-if="!startProcess">
        <div slot="header" class="clearfix">
          <span style="font-weight: bold; font-size: 20px;">{{ item.nodeName }}</span>
        </div>
        <div class="text item">
          <div :class="'finishForm' + item.nodeName" :ref="'finishForm' + item.nodeName"></div>
        </div>
      </el-card>

      <Comment :processInstanceId="processInstanceId" :key="'comment' + key"></Comment>

      <Bpmn :processInstanceId="processInstanceId" :process-key="processKey" :process-version="processVersion" :key="'bpmn' + key"></Bpmn>

      <ProcessControlInfo ref="processControlInfo" @resetInit="resetInit"></ProcessControlInfo>

    </el-dialog>

    <ProcessFollow ref="processFollow"></ProcessFollow>

    <el-dialog
      :visible.sync="openStartProcess"
      :fullscreen="false"
      :destroy-on-close="true"
      append-to-body
      :show-close="false" style="height: 800px;">
      <div style="
          border-bottom: 1px solid rgb(232,232,232);
          position: absolute;
          top: 0; left: 0;
          height: 70px; width: 100%;
          line-height: 70px; padding-left: 20px; padding-right: 20px;">
        <span style="font-weight: bold; font-size: 20px;">启动流程</span>

        <div style="float:right;">
          <el-button plain icon="el-icon-close" @click="openStartProcess = false"></el-button>
        </div>
      </div>

      <div style="margin: 40px 40px 70px 40px;">
        <el-card class="box-card" style="margin-bottom: 20px;" v-show="userList.length > 0">
          <div slot="header" class="clearfix">
            <span>用户</span>
          </div>

          <el-row  v-show="userList.length > 0">
          <el-col :span="16"><div class="grid-content bg-purple" style="padding: 10px;">
            <el-table
              ref="multipleTable"
              :data="userList"
              height="265"
              max-height="265"
              border
              tooltip-effect="dark"
              style="width: 100%;"
              @selection-change="handleSelectionChange">
              <el-table-column
                type="selection"
                align="center"
                width="55">
              </el-table-column>
              <el-table-column
                type="index"
                label="序号"
                width="55"
                align="center"
                sortable>
              </el-table-column>
              <el-table-column
                prop="nickName"
                align="center"
                label="姓名">
              </el-table-column>
              <el-table-column
                prop="phonenumber"
                align="center"
                label="手机号"
                width="150">
              </el-table-column>
              <el-table-column
                prop="deptName"
                align="center"
                label="部门名称">
              </el-table-column>
            </el-table>
          </div></el-col>
          <el-col :span="8">
            <div class="grid-content bg-purple-light" style="padding: 10px;">
              <div style="border: 1px solid #dfe6ec; width: 100%;height: 40px;padding: 10px; font-size: 16px;">
                <span style="float:left;">已选</span>
                <span style="float:right;">
                    <i style="cursor: pointer" class="el-icon-delete" @click="handleDeleteSelectUserButton()"></i>
                  </span>
              </div>
              <div style="border: 1px solid #dfe6ec; height: 226px; margin-top: -1px;padding: 10px; max-height: 226px;overflow-y: scroll;">
                <el-empty :image-size="60" v-show="!selectUserList.length > 0"></el-empty>
                <div v-for="(item,index) in selectUserList" :key="index"
                     style="padding: 10px; height: 40px; border: 1px solid #dfe6ec; margin-top: -1px;">
                  <span style="float:left;">{{ item.userId + '-' + item.nickName + '-' + item.deptName }}</span>
                  <span style="float:right;">
                      <i style="cursor: pointer" class="el-icon-delete" @click="handleDeleteSelectUserButton(item)"></i>
                    </span>
                </div>
              </div>
            </div>
          </el-col>
        </el-row>
        </el-card>

        <el-input
          type="textarea"
          :rows="2"
          placeholder="请输入流程标题"
          v-model="startProcessTitle">
        </el-input>
      </div>

      <div style="
        border-top: 1px solid rgb(232,232,232);
        position: absolute;
        bottom: 0; left: 0;
        height: 70px; width: 100%;
        line-height: 70px; padding-left: 20px; padding-right: 20px;">
        <div style="float:right; margin: 17px;">
          <el-button type="primary" style="float: right" @click="handleStartProcess()">开启</el-button>
          <el-button plain style="float: right; margin-right: 20px;" @click="openStartProcess = false">取消</el-button>
        </div>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import Comment from '@/components/Camunda/comment'
import Bpmn from '@/components/Camunda/bpmn'
import ProcessControlInfo from './processControlInfo'
import ProcessFollow from '@/components/Camunda/processFollow'

import {
  getProcessAuth,
  getProcessByUserId,
  getProcessForm,
  getProcessStartForm, getStartProcessUserList,
  startProcessByVersion
} from "@/api/camunda/camunda";
import { Form } from "@bpmn-io/form-js";
import Constant from './constant'

export default {
  name: "processControl",
  components: {
    Comment,
    Bpmn,
    ProcessControlInfo,
    ProcessFollow,
  },
  data() {
    return {
      key: null,

      openProcess: false,
      processInstanceId: undefined,
      processTitle: '',
      openStartForm: false,
      openTaskForm: false,
      isHandle: false,

      taskId: undefined,
      taskFormTitle: '',
      taskForm: undefined,

      authList: [],
      complete: Constant.Complete,

      startProcess: false,
      processList: [],
      processVersionList: [],
      processKey: null,
      processVersion: null,
      formEditor: null,

      openStartProcess: false,
      startProcessTitle: '',

      finishForm: [],

      selectUserList: [],
      userList: [],
    }
  },
  methods: {
    init(processInstanceId, processTitle, start) {
      this.reset()
      if(start) {
        this.startProcess = true
        getProcessByUserId()
          .then(({data}) => {
            this.openProcess = true
            this.processTitle = processTitle
            this.processList = data
            if(data.length > 0){
              this.processKey = data[0].processKey
              this.processVersionList = data[0].version
              if(this.processVersionList.length > 0){
                this.processVersion = this.processVersionList[0].versionNum
              }
            }
            this.handleGetStartResource()
            this.key = new Date().getTime()
          }).catch()
      }
      if(processInstanceId){
        this.processInstanceId = processInstanceId
        this.processTitle = processTitle
        this.handleProcessForm(processInstanceId)
        this.key = new Date().getTime()
      }
    },
    resetInit(type, message){
      this.$refs.processControlInfo.reset()
      this.handleProcessForm(this.processInstanceId)
      this.key = new Date().getTime()
      if(type && message){
        this.$message({type: type,message: message, duration: 1500})
      }
    },
    reset() {
      this.openProcess = false
      this.processInstanceId = undefined
      this.processTitle = ''
      this.openStartForm = false
      this.openTaskForm = false
      this.isHandle = false
      this.taskId = undefined
      this.taskFormTitle = ''
      this.authList = []
      this.taskForm = undefined
      this.startProcess = false
      this.processList = []
      this.processVersionList = []
      this.processKey = null
      this.processVersion = null
      this.formEditor = null
      this.openStartProcess = false
      this.startProcessTitle = ''
      this.selectUserList = []
      this.userList = []
    },
    handleChangeProcessKey(val) {
      this.processList.forEach((item) => {
        if(item.processKey === val){
          this.processVersionList = item.version
          if(this.processVersionList.length > 0){
            this.processVersion = this.processVersionList[0].versionNum
            this.handleGetStartResource()
            this.key = new Date().getTime()
          }
        }
      })
    },
    handleChangeProcessVersion(val) {
      this.processVersion = val
      this.handleGetStartResource()
      this.key = new Date().getTime()
    },
    handleCreateProcess() {
      if(this.formEditor){
        const submit = this.formEditor.submit()
        if(JSON.stringify(submit.errors) === '{}') {
          this.openStartProcess = true
          getStartProcessUserList(this.processKey, this.processVersion)
            .then(({data}) => {
              this.userList = data
            }).catch()
        } else {
          this.$message({type: 'warning',message: '请填写必填项'})
        }
      }
    },
    handleStartProcess() {
      if(this.userList.length > 0 && this.selectUserList.length === 0){
        this.$message({type: 'warning',message: '未选择审批用户'})
        return;
      }
      if(this.processKey === null || this.processVersion === null){
        this.$message({type: 'warning',message: '未选择流程与版本号'})
        this.openStartProcess = false
        return;
      }
      let map = {}
      if(this.formEditor){
        const submit = this.formEditor.submit()
        if(JSON.stringify(submit.errors) === '{}') {
          map = submit.data
          if(this.selectUserList.length > 0){
            const userList = []
            this.selectUserList.forEach((item) => {
              userList.push(item.userId + '-' + item.nickName + '-' + item.deptName)
            })
            map.assigneeList = userList
            console.log(userList)
          }
          if(this.startProcessTitle){
            startProcessByVersion(
              this.processKey,
              this.processVersion,
              this.startProcessTitle,
              map
            ).then(({data}) => {
              this.openStartProcess = false
              this.init(data.processInstanceId, data.processTitle)
            }).catch(()=>{
            })
          } else {
            this.$message({type: 'warning',message: '请填写流程标题'})
          }
        } else {
          this.$message({type: 'warning',message: '请填写必填项'})
          this.openStartProcess =false
        }
      }
    },
    handleGetStartResource() {
      this.openStartForm = false
      if(this.processKey !== null && this.processVersion !== null) {
        getProcessStartForm({
          processKey: this.processKey,
          version: this.processVersion
        }).then(({data}) => {
          if(this.formEditor) {
            this.formEditor.destroy()
          }
          if(data){
            this.openStartForm = true
            this.$nextTick(() => {
              // 初始化表单
              this.formEditor = new Form({
                container: this.$refs.startForm
              })
              this.formEditor.importSchema(JSON.parse(data))
            })
          }
        }).catch()

      }
    },
    handleProcessAuth() {
      getProcessAuth(this.taskId)
        .then(({data}) => {
          this.authList = data
        }).catch()
    },
    handleProcessForm(processInstanceId) {
      getProcessForm(processInstanceId)
        .then(({data}) => {
          this.openProcess = true
          this.isHandle = data.isHandle
          this.finishForm.forEach((item) => {
            if(item.formEditor){
              item.formEditor.destroy()
            }
          })
          this.finishForm = data.finishedForms
          let variables = data.variables
          if(variables === null){
            variables = {}
          }

          if(data.taskId) {
            this.taskFormTitle = data.activityName
            this.taskId = data.taskId

            // 获取当前任务的权限操作
            this.handleProcessAuth()
          } else {
            this.authList = []
          }

          if(data.startForm) {
            this.openStartForm = true
            const startForm = JSON.parse(data.startForm)
            startForm.components.forEach((component) => {
              component.disabled = true
              const val = variables[component.key]
              if(val) {
                component.defaultValue = val
              }
            })

            if(this.formEditor) {
              this.formEditor.destroy()
            }
            this.$nextTick(() => {
              // 初始化开始表单
              this.formEditor = new Form({
                container: this.$refs.startForm
              })
              this.formEditor.importSchema(startForm)

              // 初始化完成表单
              console.log(this.finishForm)
              this.finishForm.forEach((item) => {
                const form = JSON.parse(item.form)
                form.components.forEach((component) => {
                  component.disabled = true
                  const val = variables[component.key]
                  if(val) {
                    component.defaultValue = val
                  }
                })
                item.formEditor = new Form({
                  container: this.$refs['finishForm' + item.nodeName][0]
                })
                item.formEditor.importSchema(form)
              })
            })
          } else {
            this.openStartForm = false
          }

          if(data.form) {
            this.openTaskForm = true
            this.$nextTick(() => {
              const formTask = JSON.parse(data.form)
              formTask.components.forEach((component) => {
                const val = variables[component.key]
                if(val) {
                  component.defaultValue = val
                }
              })

              if(this.taskForm){
                this.taskForm.destroy()
              }

              this.taskForm = new Form({
                container: this.$refs.taskForm
              })
              this.taskForm.importSchema(formTask)
            })

          } else {
            this.openTaskForm = false
          }
        })
    },
    // 办理
    handleCompleteButton() {
      if(this.taskId){
        let map = {}
        if(this.taskForm){
          map = this.taskForm.submit().data
        }
        this.$refs.processControlInfo.init(
          Constant.Complete, this.taskId, map)
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 完成委托
    handleCompleteDelegateButton() {
      if(this.taskId){
        let map = {}
        if(this.taskForm){
          const submit = this.taskForm.submit()
          if(JSON.stringify(submit.errors) === '{}') {
            map = submit.data
          } else {
            this.$message({type: 'warning',message: '请填写必填项'})
          }
        }
        this.$refs.processControlInfo.init(
          Constant.CompleteDelegate, this.taskId, map)
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 加签
    handleAddSignButton() {
      if(this.taskId){
        this.$refs.processControlInfo.init(
          Constant.AddSign, this.taskId, {})
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 减签
    handleDeleteSignButton() {
      if(this.taskId){
        this.$refs.processControlInfo.init(
          Constant.DeleteSign, this.taskId, {})
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 委托
    handleDelegateButton() {
      if(this.taskId){
        this.$refs.processControlInfo.init(
          Constant.Delegate, this.taskId, {})
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 取消委托
    handleCancelDelegateButton() {
      if(this.taskId){
        this.$refs.processControlInfo.init(
          Constant.CancelDelegate, this.taskId, {})
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 转办
    handleRelayCompleteButton() {
      if(this.taskId){
        this.$refs.processControlInfo.init(
          Constant.RelayComplete, this.taskId, {})
      } else {
        this.$message({type: 'error',message: '任务不存在'})
      }
    },
    // 流程跟踪
    handleProcessFollowButton() {
      this.$refs.processFollow.init(this.processInstanceId)
    },
    handleCloseProcess() {
      this.$emit('init')
      this.reset()
      this.openProcess = false
    },
    // 多选
    handleSelectionChange(val) {
      if(val) {
        this.selectUserList = val;
      }
    },
    // 多选操作
    handleDeleteSelectUserButton(rows) {
      if (rows) {
        this.$refs.multipleTable.toggleRowSelection(rows);
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
  },
}
</script>

<style scoped>

</style>
